<?php
namespace haibao\classlibrary\cms\common;

class MailHandler{
    
	private static $server;
	private static $port;
	private static $path;
	
	public static function setConfig($server, $port=80, $path='/'){
		self::$server = $server;
		self::$port = $port;
		self::$path = $path;
	}
	
	public static function sendMail($mailModel){
    	$boundary = '---------------------------'.substr(md5(rand(0,32000)),0,10);        
    	$encoded = self::parseMailModel($mailModel,$boundary);
        $length = strlen($encoded);
        $fp = @fsockopen(self::$server, self::$port);
        if(!$fp){
            throw new CommonException('conection error');
        }
        fputs($fp, "POST ".self::$path." HTTP/1.0\r\n");
        fputs($fp, "Host: ".self::$server.":".self::$port."\r\n");
        fputs($fp, "Content-type: multipart/form-data; boundary=$boundary\r\n");
        fputs($fp, "Content-length: ".$length."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $encoded);
        $line = fgets($fp,1024);
        $results = "";
        $inheader = 1;
        while(!feof($fp)){
            $line = fgets($fp,1024);
            if($inheader && ($line == "\r\n" || $line == "\r\r\n")){
                $inheader = 0;
            }
            elseif(!$inheader){
                $results .= $line;
            }
        }
        
        fclose($fp);
    }
    
    private static function parseMailModel($mailModel, $boundary){
        $boundary_2 = '--'.$boundary;
        $encoded = '';
        
        if ($mailModel->Reply){
	        $encoded .= self::getItemContent('reply',$mailModel->Reply,$boundary_2);
        }
        if ($mailModel->Name){
	        $encoded .= self::getItemContent('cname',$mailModel->Name,$boundary_2);
        }
        if ($mailModel->Bcc){
        	$encoded .= self::getItemContent('bcc', $mailModel->Bcc, $boundary_2);
        }
        
        $encoded .= self::getItemContent('mailfrom',$mailModel->From,$boundary_2);
        $encoded .= self::getItemContent('mailto',implode(',',$mailModel->To),$boundary_2);
        $encoded .= self::getItemContent('subject',$mailModel->Subject,$boundary_2);
        $encoded .= self::getItemContent('content',$mailModel->Content,$boundary_2);
        $encoded .= self::getItemContent('sender',$mailModel->Sender,$boundary_2);
        
        $parameters = $mailModel->getParameters();
        if ($parameters){
	        $encoded .= self::getItemContent('param',self::getParametersString($parameters),$boundary_2);
        }
        
        $attachements = $mailModel->getAttachments();
        if ($attachements){
            $encoded .= self::getAttachmentsContent($attachements,$boundary,$boundary_2);
        }

		$encoded .= "\r\n".$boundary_2."--\r\n";

		return $encoded;
    }
    
    private static function getItemContent($itemName,$itemValue,$boundary_2){
        $encoded = $boundary_2."\r\nContent-Disposition: form-data; name=\"".$itemName."\"\r\n\r\n";
        $encoded .= $itemValue. "\r\n";
        
        return $encoded;
    }
    
    private static function getParametersString($parameters){
        $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><d />");
        foreach($parameters as $mail=>$parameters){
            $node = $xml->addChild("p");
            $node->addAttribute("t",$mail);
            foreach($parameters as $k => $v){
                $childNode = $node->addChild("i");
                $childNode->addAttribute("k",$k);
                $childNode->addAttribute("v",$v);
            }
        }
        
        return $xml->asXML();
    }
    
    private static function getAttachmentsContent($attachements,$boundary,$boundary_2){
    	$content = '';
    	$num = 0;
        foreach($attachements as $fileName=>$fileContent){
            $fileName = iconv('UTF-8','GBK',$fileName);
            $type = self::getFileType($fileName);
            $content .= $boundary_2 . "\r\nContent-Disposition: form-data; name=\"file".strval($num)."\"; filename=\"".$fileName."\"\r\nContent-Type: ".$type.";\r\n\r\n";
            $content .= $fileContent . "\r\n";
            $num++;
        }
        
        return $content;
    }
    
    private static function getFileType($fileName){
    	$type = 'text/html';
        $ext = strrchr($fileName, ".");
        switch($ext)
        {
            case '.gif': 
            	$type = "image/gif";
	            break;
            case '.jpg': 
            	$type = "image/jpeg";
            	break;
            case '.png': 
            	$type = "image/png";
            	break;
            case '.html': 
            	$type="text/html";
            	break;
        }
        
        return $type;
    }
}

?>
